/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package service

import (
	"mime/multipart"

	"icep/bean/model"
	"icep/bean/param"
	"icep/chain/client"
	"icep/common/constant"
	"icep/common/crypto/gm"
)

func (is *IcepService) VideoObtainEvidence(files []*multipart.FileHeader, evidenceId, currentUserId, userPrvKey string,
	chainClient *client.IchainClient, iden *model.Identity, para param.CreateObtainEvidenceParam) {
	//计算文件哈希
	totalHash, filesHash, _, err := GetDataHash(files)
	if err != nil {
		log.Errorf("err: %v", err)
		DealWithErr(is.DbEngine, evidenceId)
		return
	}
	//签名
	hashSignature := gm.Sign(userPrvKey, []byte(totalHash))
	//保存签名到签名表
	err = InsertSignature(is.DbEngine, evidenceId, hashSignature)
	if err != nil {
		log.Errorf("err: %v", err)
		DealWithErr(is.DbEngine, evidenceId)
		return
	}
	//上传云存储获得URL
	urls, err := UploadVideoFiles(evidenceId, files)
	if err != nil {
		log.Errorf("err: %v", err)
		DealWithErr(is.DbEngine, evidenceId)
		return
	}
	//存入取证明细表
	err = InsertObtainEvidenceDetail(is.DbEngine, evidenceId, files, filesHash, urls)
	if err != nil {
		log.Errorf("err: %v", err)
		DealWithErr(is.DbEngine, evidenceId)
		return
	}

	//上链
	txId, txTime, err := InsertChain(chainClient, evidenceId, hashSignature, totalHash, para, files, filesHash, urls)
	if err != nil {
		log.Errorf("err: %v", err)
		DealWithErr(is.DbEngine, evidenceId)
		return
	}
	res := Result{TxId: txId, TxTime: txTime}

	letterParam := is.GetDepositoryLetterParam(currentUserId)
	//生成存证函
	letterUrl, err := GeneAttestLetter(chainClient, letterParam, evidenceId, txId, txTime, totalHash, constant.ObtainTypeVideo)
	if err != nil {
		DealWithErr(is.DbEngine, evidenceId)
		return
	}

	//将取证信息存入取证表
	err = UpdateObtainEvidenceData(is.DbEngine, evidenceId, iden.IdentityId, constant.ObtainStatusSuccess, letterUrl, &res)
	if err != nil {
		log.Errorf("err: %v", err)
		return
	}
}
